package keeto.com.vn.classified.ui;

/*
 * product_cate_4*/
import java.util.ArrayList;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classfied.model.Category;
import keeto.com.vn.classified.adapter.AdapterProductViewAll;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.menutab.IMenuTabConfig;
import keeto.com.vn.classified.menutab.MenuTabAdapter;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.widgets.LogoutDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class IAProductCateIndexActivity extends Activity implements OnClickListener, OnRefreshListener<ListView> {
	private Button btn_editor_warranty;
	private EditText edt_search_warranty_store;
	private ImageButton btn_search_warranty;
	private Category mParentCate = null;
	private Category subCategory = null;
	private Area mArea = null;
	private final static String EXTRA_PARENT_CATEGORY = "ParentCategory";
	private final static String EXTRA_SUB_CATEGORY = "SubCategory";
	private final static String EXTRA_SELECTED_AREA = "SelectedArea";
	private LinearLayout ll_fb_sortby;
	private LinearLayout ll_fb_post;
	private LinearLayout ll_fb_handbook;

	private PullToRefreshListView list_product;
	private ProgressBar mProgressbar;

	private ImageButton btnMenu;
	private ImageButton btnHome;
	private ImageView btnSearchGlobal;

	private DrawerLayout drawerLayoutMenuTab;
	private ListView mDrawerList;
	BuiltinServiceManager mBuiltinServiceManager = null;
	private BuiltinService builtservice = null;
	private MenuTabAdapter tabAdapter;
	private AQuery mQuery ;

	int position;
	private static int SORTBY = 1;

	private Animation mAnimation;
	private Animation mAnimation1;
	private LinearLayout mFloatingbar;
	private Handler mHandler = new Handler();
	private Listener mListener = new Listener();

	private AdapterProductViewAll adapter;
	private static InUIThreadHandler mReturnCodeHandler = null;

	private static int PageNumber = 1;
	private int PageLimit=10;
	private ArrayList<ListItemEntity> list = new ArrayList<ListItemEntity>();

	public static void getIntentView(Activity context, Category category,
			Area area, Category subcategory) {
		Intent i = new Intent(context, IAProductCateIndexActivity.class);
		i.putExtra(EXTRA_SELECTED_AREA, area);
		i.putExtra(EXTRA_PARENT_CATEGORY, category);
		i.putExtra(EXTRA_SUB_CATEGORY, subcategory);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.product_cate_4);
		mReturnCodeHandler = new InUIThreadHandler();
		Intent i = getIntent();
		Bundle extras = i.getExtras();
		mArea = (Area) extras.get(EXTRA_SELECTED_AREA);
		mParentCate = (Category) extras.get(EXTRA_PARENT_CATEGORY);
		subCategory = (Category) extras.get(EXTRA_SUB_CATEGORY);
		mQuery = new AQuery(this);
		initUIComponent();
		initMenuData();
		PageNumber = 1;
		LoadItemSortBy(SORTBY);
	}

	private void initUIComponent() {
		mFloatingbar = (LinearLayout) findViewById(R.id.bottom_floatingbar);
		mAnimation = AnimationUtils.loadAnimation(this,
				R.anim.animation_show_fb1);
		mAnimation1 = AnimationUtils.loadAnimation(this,
				R.anim.animation_hide_fb1);

		mFloatingbar = (LinearLayout)findViewById(R.id.ll_floating_bar_store_list);
		ll_fb_sortby = (LinearLayout) findViewById(R.id.ll_fb_Sortby);
		ll_fb_post = (LinearLayout) findViewById(R.id.ll_fb_post);
		ll_fb_handbook = (LinearLayout) findViewById(R.id.ll_fb_handbook);
		drawerLayoutMenuTab = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.drawer);

		mProgressbar = (ProgressBar) findViewById(R.id.pg_load);
		mProgressbar.setVisibility(View.GONE);

		list_product = (PullToRefreshListView) findViewById(R.id.list_product);
		list_product.setMode(Mode.BOTH);

		btnMenu = (ImageButton) findViewById(R.id.btn_title_na_menu);
		btnHome = (ImageButton) findViewById(R.id.btn_title_logo_home);
		btnSearchGlobal = (ImageView) findViewById(R.id.btn_title_search_home);
		btnMenu.setOnClickListener(this);
		btnSearchGlobal.setOnClickListener(this);
		btnHome.setOnClickListener(this);

		btn_editor_warranty = (Button) findViewById(R.id.btn_editor_warranty);
		edt_search_warranty_store = (EditText) findViewById(R.id.edt_search_warranty_store);
		btn_search_warranty = (ImageButton) findViewById(R.id.btn_search_warranty);
		btn_search_warranty.setOnClickListener(this);
		btn_editor_warranty.setOnClickListener(this);

		edt_search_warranty_store.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					String keysearch = edt_search_warranty_store.getText()
							.toString();
					if (subCategory == null){
						ProductsActivity.actionSearchByCategory(IAProductCateIndexActivity.this, mParentCate.getRemoteId(), keysearch);
					}else{
						ProductsActivity.actionSearchByCategory(IAProductCateIndexActivity.this, subCategory.getRemoteId(), keysearch);

					}
				}
				return false;
			}
		});


		adapter = new AdapterProductViewAll(this, list,mQuery);
		list_product.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		list_product.setOnRefreshListener(this);

		if (subCategory == null){
			btn_editor_warranty.setHint(mParentCate.getName());
			edt_search_warranty_store.setHint(mParentCate.getName());

		}else{
			btn_editor_warranty.setHint(subCategory.getName());
			edt_search_warranty_store.setHint(subCategory.getName());

		}

		mAnimation = AnimationUtils.loadAnimation(this, R.anim.animation_show_fb);
		mAnimation1 = AnimationUtils.loadAnimation(this, R.anim.animation_hide_fb);
		mAnimation1.setAnimationListener(new Animation.AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				mFloatingbar.setVisibility(View.GONE);
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						if (mFloatingbar.getVisibility() == View.GONE){
							mFloatingbar.startAnimation(mAnimation);
							mFloatingbar.setVisibility(View.VISIBLE);
						}
					}
				}, 4500);
			}
		});
		ll_fb_sortby.setOnClickListener(this);
		ll_fb_post.setOnClickListener(this);
		ll_fb_handbook.setOnClickListener(this);
	}

	public void onBackPressed() {
		if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
			drawerLayoutMenuTab.closeDrawers();
			return;
		} else {
			super.onBackPressed();
		}
	};

	private void sortbyView() {
		AlertDialog.Builder mBuilder = new AlertDialog.Builder(
				IAProductCateIndexActivity.this);
		mBuilder.setTitle(this.getString(R.string.sort_by_tittle));
		mBuilder.setItems(R.array.sortbyfloatingbarproduct,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				PageNumber = 1;
				list.clear();
				adapter.notifyDataSetChanged();
				mProgressbar.setVisibility(View.VISIBLE);
				switch (which) {
				case 0:
					SORTBY = 4; // nhan vao gia ban
					LoadItemSortBy(SORTBY);
					break;
				case 1:
					SORTBY = 1; // nhan vao thoi gian
					LoadItemSortBy(SORTBY);
					break;
				case 2:
					SORTBY = 2; // nhan vao danh gia
					LoadItemSortBy(SORTBY);
					break;
				default:
					break;
				}
			}
		});
		Dialog dialog = mBuilder.create();
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
	}

	private void LoadItemSortBy(final int Sortby) {
		final String hightlight = "[\"suggestproduct\"]";
		mProgressbar.setVisibility(View.VISIBLE);
		if (subCategory == null){
			ClassifiedCore.getInstance(IAProductCateIndexActivity.this).taskGetProductSubCate(mListener, hightlight, "0",Integer.parseInt(mParentCate.getRemoteId()), PageLimit,"products", "", PageNumber, Sortby);
		}else{
			ClassifiedCore.getInstance(IAProductCateIndexActivity.this).taskGetProductSubCate(mListener, hightlight, "0",Integer.parseInt(subCategory.getRemoteId()), PageLimit,"products", "", PageNumber, Sortby);

		}
	}

	private void initMenuData() {
		if (builtservice == null) {
			tabAdapter = new MenuTabAdapter(IAProductCateIndexActivity.this,
					false, IMenuTabConfig.MENU_HOME);
		} else {
			tabAdapter = new MenuTabAdapter(IAProductCateIndexActivity.this,
					true, IMenuTabConfig.MENU_HOME);
			tabAdapter.setUsername(builtservice.getUserName());
		}
		mDrawerList.setAdapter(tabAdapter);
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (tabAdapter.getTabModel() != null) {
					int index = tabAdapter.getTabModel().get(position)
							.getMenutab_key();
					switch (index) {
					case IMenuTabConfig.MENU_HOME:
						drawerLayoutMenuTab.closeDrawers();
						CategoriesActivity.launchCategoriesView(
								IAProductCateIndexActivity.this, mArea);
						break;
					case IMenuTabConfig.MENU_AREA:
						drawerLayoutMenuTab.closeDrawers();
						ProvincesActivity
						.actionChangeCityLaunch(IAProductCateIndexActivity.this);
						break;
					case IMenuTabConfig.MENU_PROFILE_NAME:
						if (builtservice == null) {
							drawerLayoutMenuTab.closeDrawers();
							LoginActivity
							.actionLaunch(IAProductCateIndexActivity.this);
						} else {
							drawerLayoutMenuTab.closeDrawers();
							UserProfileActivity
							.actionLaunch(IAProductCateIndexActivity.this);
						}

						break;
					case IMenuTabConfig.MENU_INTEREST:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity
						.actionViewFavorites(IAProductCateIndexActivity.this);
						break;
					case IMenuTabConfig.MENU_POSTED:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity
						.actionViewPosted(IAProductCateIndexActivity.this);
						break;
					case IMenuTabConfig.MENU_HISTORY:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity
						.actionViewHistory(IAProductCateIndexActivity.this);

						break;
					case IMenuTabConfig.MENU_LOGOUT:
						drawerLayoutMenuTab.closeDrawers();
						LogoutDialog dialog = new LogoutDialog(
								IAProductCateIndexActivity.this);
						dialog.show();
						break;

					case IMenuTabConfig.MENU_POST:
						drawerLayoutMenuTab.closeDrawers();
						PostProductActivity
						.actionLaunch(IAProductCateIndexActivity.this);
						break;

					default:
						break;
					}

				}
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(IAProductCateIndexActivity.this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		initMenuData();
		if (tabAdapter != null){
			for (int i=0;i<tabAdapter.getTabModel().size();i++){
				if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_HOME){
					tabAdapter.getTabModel().get(i).setNameMenu(mParentCate.getName());
					break;
				}
			}
			tabAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ProvincesActivity.ACTION_CHANGE_AREA && resultCode == RESULT_OK){
			mArea =  IAManager.getInstance(this).getMyArea();
			if (tabAdapter != null && mArea != null){
				for (int i=0;i<tabAdapter.getTabModel().size();i++){
					if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_AREA){
						tabAdapter.getTabModel().get(i).setNameMenu(mArea.getName());
						break;
					}
				}
				tabAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}



	class Listener extends ClassifiedListener {
		@Override
		public void finishGetProductCateFour(final int returnCode,
				final ArrayList<ListItemEntity> list_productcatefour,
				final int count) {
			super.finishGetProductCateFour(returnCode, list_productcatefour,
					count);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mProgressbar.setVisibility(View.GONE);
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (PageNumber < count) {
							PageNumber += 1;
						} else {
							PageNumber = -1;
						}
						if (list_productcatefour != null
								&& list_productcatefour.size() > 0) {
							list.addAll(list_productcatefour);

						}
					} else {
						mReturnCodeHandler.takeActionByReturnCode(
								IAProductCateIndexActivity.this, returnCode,
								true);
					}
					adapter.notifyDataSetChanged();
					list_product.onRefreshComplete();
				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_title_na_menu:
			if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
				drawerLayoutMenuTab.closeDrawers();
			} else {
				drawerLayoutMenuTab.openDrawer(mDrawerList);
			}
			break;
		case R.id.btn_title_search_home:
			ProductsActivity.actionSearchGlobal(this);
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(this);
			break;
		case R.id.btn_editor_warranty:
			CategoriesActivity.launchCategoriesView(IAProductCateIndexActivity.this, mArea);
			break;
		case R.id.btn_search_warranty:
			String keysearch = edt_search_warranty_store.getText().toString();
			if (subCategory == null){
				ProductsActivity.actionSearchByCategory(IAProductCateIndexActivity.this, mParentCate.getRemoteId(), keysearch);
			}else{
				ProductsActivity.actionSearchByCategory(IAProductCateIndexActivity.this, subCategory.getRemoteId(), keysearch);

			}
			break;
		case R.id.ll_fb_Sortby:
			sortbyView();
			break;
		case R.id.ll_fb_post:
			PostProductActivity
			.actionLaunch(IAProductCateIndexActivity.this);
			break;
		case R.id.ll_fb_handbook:
			if (builtservice != null){
				HandBookActivity
				.actionLaunchIntent(IAProductCateIndexActivity.this);
			}else{
				LoginActivity.actionLaunch(IAProductCateIndexActivity.this);
			}


		default:
			break;
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		if (PageNumber > 0) {
			if (refreshView.getCurrentMode() == Mode.PULL_FROM_START){
				PageNumber = 1;
				list.clear();
				adapter.notifyDataSetChanged();
			}
			LoadItemSortBy(SORTBY);
		}else {
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					list_product.onRefreshComplete();
				}
			});
		}
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}
}
